package vip.liux.contracts.shared.util;

import jakarta.validation.*;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Set;

public class ValidatorUtils {

    private static Validator validator;

    static {
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            validator = factory.getValidator();
        } catch (Exception ignore) {
        }
    }

    public static void validate(Object object, Class<?>... groups) {
        validate(validator, object, groups);
    }

    public static void validate(Validator validator, Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (CollectionUtils.isNotEmpty(constraintViolations)) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }
}
